package com.sikao.app.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.sikao.app.R;
import com.sikao.app.adapter.GvAddStepPricesTypeProfilePicItemAdapter;
import com.sikao.app.app.AppManager;
import com.sikao.app.bean.AddGoodsStepThreeBean;
import com.sikao.app.bean.GetImageInfoBean;
import com.sikao.app.bean.GetImageInfoSubmitBean;
import com.sikao.app.bean.ReadAddGoodsStepThreeBean;
import com.sikao.app.bean.ReadAddGoodsStepThreeSubmitBean;
import com.sikao.app.bean.UploadPicturesBean;
import com.sikao.app.dao.AddGoodsStepThreeModel;
import com.sikao.app.dao.GetImageInfoModel;
import com.sikao.app.dao.ReadAddGoodsStepThreeModel;
import com.sikao.app.dao.UploadPicturesModel;
import com.sikao.app.myinterface.Callback;
import com.sikao.app.net.HttpApi;
import com.sikao.app.net.OnNetBackListener;
import com.sikao.app.ui.base.BaseActivity;
import com.sikao.app.utils.JSONUtil;
import com.sikao.app.utils.Utils;
import com.sikao.app.view.MyGridView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import  com.sikao.app.bean.AddGoodsStepThreeSubmitBean;

import static com.sikao.app.ui.AddGoodsStepTwoActivity.canEdit;

/**
 * Created by Sun on 2016/8/15.
 * 编辑检验报告照片  发布商品第三步
 */
public class AddGoodsStepThreeActivity extends BaseActivity implements View.OnClickListener {

    private TextView titleTv;
    private TextView title_right_tv;
    private TextView title_left_tv;
    private ImageView backIv;
    private MyGridView gv_release_goods_store_pic;
    private Button bt_save;
    private UploadPicturesModel uploadPicturesModel;
    String objectId;//商品ID
    AddGoodsStepThreeSubmitBean addGoodsStepThreeSubmitBean =new AddGoodsStepThreeSubmitBean();

    GvAddStepPricesTypeProfilePicItemAdapter gvAddStepPricesTypeProfilePicItemAdapter;//图样适配器(复用图样的)
    private List<String> picList = new ArrayList<String>();//检验报告图片
    int picIndex=0;//点击的图片的下标
     String checkReport="";
    public static final int REQUEST_GET_PHOTO=1001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_release_goods_step_three);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();

        objectId = intent.getStringExtra("objectId");
        Utils.showLog("=======objectId:"+objectId);

            // 从网络中获取图片地址
            picList.clear();
            //从网络获取 给picList赋值，同时添加一个空值
            //获取picids
            getPicIds();

    }

    private void getPicIds() {
        ReadAddGoodsStepThreeSubmitBean readAddGoodsStepThreeSubmitBean = new ReadAddGoodsStepThreeSubmitBean();
        readAddGoodsStepThreeSubmitBean.setObjectId(objectId);
        ReadAddGoodsStepThreeModel ReadAddGoodsStepThreeModel = new ReadAddGoodsStepThreeModel(this, new OnNetBackListener<ReadAddGoodsStepThreeBean>() {
            @Override
            public void netBack(ReadAddGoodsStepThreeBean data) {
                if (data == null) {
                    Toast.makeText(AddGoodsStepThreeActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
                } else {
                    if (data.getStatus() == 1) {
                      String check_report =  data.getRes().getCheck_report();
                        if (null!=check_report&&check_report.length()>0){
                            //获取图片信息
                            checkReport = check_report;
                            getImageInfoFromIn();
                        }else{
                            checkReport="";
                            picList.add("");//刚进去默认有一张图片
                            gvAddStepPricesTypeProfilePicItemAdapter.notifyDataSetChanged();
                        }
                    } else {
                        Toast.makeText(AddGoodsStepThreeActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        ReadAddGoodsStepThreeModel.request(JSONUtil.toJSON(readAddGoodsStepThreeSubmitBean),true);
    }

    private void getImageInfoFromIn() {
        GetImageInfoSubmitBean getImageInfoSubmitBean = new GetImageInfoSubmitBean();
        getImageInfoSubmitBean.setIds(checkReport);
        GetImageInfoModel getImageInfoModel = new GetImageInfoModel(this, new OnNetBackListener<GetImageInfoBean>() {
            @Override
            public void netBack(GetImageInfoBean data) {
                if (data == null) {
                    Toast.makeText(AddGoodsStepThreeActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
                } else {
                    if (data.getStatus() == 1) {
                        for (GetImageInfoBean.ResBean resBean:data.getRes()){
                            picList.add(HttpApi.BANNERUTL+resBean.getUrl());
                        }
                        picList.add("");
                        gvAddStepPricesTypeProfilePicItemAdapter.notifyDataSetChanged();
                    } else {
                        Toast.makeText(AddGoodsStepThreeActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        getImageInfoModel.request(JSONUtil.toJSON(getImageInfoSubmitBean),true);

    }

    @Override
    protected void initView() {
        titleTv = (TextView) findViewById(R.id.title_middle_tv);
        title_right_tv = (TextView) findViewById(R.id.title_right_tv);
        title_left_tv = (TextView) findViewById(R.id.title_left_tv);
        bt_save = (Button) findViewById(R.id.bt_save);

        backIv = (ImageView) findViewById(R.id.title_left_img);
        gv_release_goods_store_pic = (MyGridView) findViewById(R.id.gv_release_goods_store_pic);

        //需要修改 这里获取重新读取的第三步 来获得图片信息
    }

    @Override
    protected void initListener() {
        title_right_tv.setOnClickListener(this);
        title_left_tv.setOnClickListener(this);
        backIv.setOnClickListener(this);
        bt_save.setOnClickListener(this);
    }

    @Override
    protected void init() {
        titleTv.setText("检验报告");
        backIv.setVisibility(View.VISIBLE);
        title_right_tv.setVisibility(View.VISIBLE);
        title_right_tv.setText("退出");
        title_left_tv.setVisibility(View.VISIBLE);
        title_left_tv.setText("上一步");

        if (canEdit){
            bt_save.setVisibility(View.VISIBLE);
        }else{
            bt_save.setVisibility(View.GONE);
        }

        gvAddStepPricesTypeProfilePicItemAdapter=new GvAddStepPricesTypeProfilePicItemAdapter(this, picList, new Callback() {
            @Override
            public void notice(int position) {

                if(canEdit) {//如果待审核等状态照片不能再编辑  picIndex =position;
                    picIndex = position;
                    if (position == (picList.size() - 1)) {//第一次点击或者点的是最后一个
                        Intent intent = new Intent(AddGoodsStepThreeActivity.this, SelectPictureActivity.class);
                        startActivityForResult(intent, REQUEST_GET_PHOTO);
                        overridePendingTransition(R.anim.bottom_push_in, R.anim.bottom_push_out);
                    } else {
                        createDialog(position);
                    }
                }

            }
        });
        gv_release_goods_store_pic.setAdapter(gvAddStepPricesTypeProfilePicItemAdapter);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_GET_PHOTO:
                    String picturePath = data.getStringExtra("path");
                    picList.set(picIndex,picturePath);
                    //上传图片
                    uploadPicture(picIndex+".png",picturePath);
                    //添加一个新的空的照片
                    //添加一个新的空的照片
                    picList.add("");
                    gvAddStepPricesTypeProfilePicItemAdapter.notifyDataSetChanged();
                    break;
                default:
                    break;
            }
        }
    }

    private void uploadPicture(String type, String picturePath) {
        if (uploadPicturesModel == null) {
            uploadPicturesModel = new UploadPicturesModel(this, new OnNetBackListener<UploadPicturesBean>() {
                @Override
                public void netBack(UploadPicturesBean data) {
                    if (data == null) {
                        Toast.makeText(AddGoodsStepThreeActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (data.getStatus().equals("1")) {
                        String id = data.getRes().getArr().get(0).getId();
                        if (TextUtils.isEmpty(checkReport)){
                            checkReport=id;
                        }else{
                            checkReport=checkReport+","+id;
                        }
                        Utils.showLog("=======检验报告添加后checkReport：" + checkReport);
                    } else {
                        Toast.makeText(AddGoodsStepThreeActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
        Map<String, String> map = new HashMap<>();
        map.put(type, picturePath);
        uploadPicturesModel.request(map, true);
    }

    private void createDialog(final int position){
        AlertDialog dialog;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("确认删除吗?");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
               picList.remove(position);
                //从checkReport中去除
                if (TextUtils.isEmpty(checkReport)){
                    checkReport="";
                }else{
                    String[] sp = checkReport.split(",");
                    sp[position]=null;
                    checkReport="";
                    for(int i=0;i<sp.length;i++){
                        if(sp[i]!=null){
                            if("".equals(checkReport)){
                                checkReport=sp[i];
                            }else{
                                checkReport=checkReport+","+sp[i];
                            }
                        }
                    }
                }
                //
                Utils.showLog("=======检验报告删除后checkReport：" + checkReport);
                gvAddStepPricesTypeProfilePicItemAdapter.notifyDataSetChanged();

            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog = builder.create();
        dialog.show();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.title_left_img :
                finish();
                break;
            case R.id.title_left_tv :
                finish();
                break;
            case R.id.title_right_tv ://退出到卖家中心
                AppManager appManager =AppManager.getAppManager();
                appManager.toSeller();
                break;
            case  R.id.bt_save://保存
                saveGoods();

                break;
            default:
            break;
        }
    }

    private void saveGoods() {

        addGoodsStepThreeSubmitBean.setObjectId(objectId);
        addGoodsStepThreeSubmitBean.setCheckReport(checkReport);

    new AddGoodsStepThreeModel(this, new OnNetBackListener<AddGoodsStepThreeBean>() {
        @Override
        public void netBack(AddGoodsStepThreeBean data) {
            if (data == null) {
                Toast.makeText(AddGoodsStepThreeActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
            } else {
                if (data.getStatus() == 1) {//发布商品成功
                    Toast.makeText(AddGoodsStepThreeActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
                    //返回卖家中心
                    AppManager appManager =AppManager.getAppManager();
                    appManager.toSeller();
                } else {
                    Toast.makeText(AddGoodsStepThreeActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }
        }
    }).request(JSONUtil.toJSON(addGoodsStepThreeSubmitBean),true);

    }


}